package ru.spbu.math.android.cbrf.charts;

import math.spbu.ru.historycharts.ChartFactory;
import math.spbu.ru.historycharts.ChartsView;
import ru.spbu.math.android.cbrf.R;
import ru.spbu.math.android.cbrf.view.WidgetProvider;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class ChartsActivity extends Activity {	
	
	private String rateTypeId;
	private static ChartsView view;
	private DateDialog dateDialog;
	private DataProvider provider;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		
		Bundle extras = getIntent().getExtras();
		rateTypeId = extras.getString(WidgetProvider.RATE_TYPE_ID);
		Log.d("BNV ChartsActivity", "rateTypeId "+rateTypeId);
		
		try{
		provider = new DataProvider(this, rateTypeId);
		}catch (Exception e) {			
			error(e);
		}
		
		view = ChartFactory.getTimeChartView(this, provider);
		setContentView(view);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, SET_DATE, 0,R.string.Set_Date);	
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
			case ADD_CHART:
				// addAlret.show();
				return true;
			case DELETE_CHART:
				// deleteChart();
				return true;
			case SET_DATE:
				if (dateDialog == null)
					dateDialog = new DateDialog(this, provider);
				dateDialog.show();
				return true;
		}
		return false;
	}

	public static void repaintView() {
		view.repaint();		
	}	
	
	public void error(Exception e){
		Log.e("ChartsActivity", "on new DataProvider", e);
		CharSequence text = "Error";
		Toast toast = Toast.makeText(ChartsActivity.this, text,
				Toast.LENGTH_SHORT);
		toast.show();
		finish();
	}
	
	public static View getView() {
		return view;		
	}	
	
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		 boolean ret = super.onKeyDown(keyCode, event);
//		 if (keyCode == 4){
//			 view = null;
//			 finish();
//		 }
//		 return ret;
//	}
	
	private final int ADD_CHART = 1, DELETE_CHART = 2, SET_DATE = 3;
}